﻿<template>
  <div class="payable-detail-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <button class="btn-primary" @click="showCreate = true">新建</button>
        <div class="filter-item">
          <label>结算类型</label>
            <select v-model="settlementType">
              <option value="">全部</option>
              <option :value="0">现结</option>
              <option :value="1">月结</option>
              <option :value="2">货到付款</option>
            </select>
        </div>
        <div class="actions">
          <button class="btn-primary" @click="onSearch">搜索</button>
          <button class="btn-secondary" @click="onReset">重置</button>
        </div>
      </div>
    </div>

    <!-- 新建模态框 -->
    <div v-if="showCreate" class="create-modal">
      <div class="modal-overlay" @click="closeCreate"></div>
      <div class="modal-content">
        <div class="modal-header">
          <span class="modal-title">新增应付明细</span>
          <button class="close-btn" @click="closeCreate">×</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-group">
              <label class="required">供应商ID</label>
              <input type="number" v-model="createForm.supplierId" placeholder="请输入供应商ID" min="1">
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>采购订单ID</label>
              <input type="number" v-model="createForm.purchaseOrderId" placeholder="请输入采购订单ID" min="1">
            </div>
            <div class="form-group">
              <label>对账单ID</label>
              <input type="number" v-model="createForm.reconciliationId" placeholder="请输入对账单ID" min="1">
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>应付类型</label>
              <select v-model="createForm.payableType">
                <option value="">请选择</option>
                <option :value="1">采购应付</option>
                <option :value="2">其他应付</option>
              </select>
            </div>
            <div class="form-group">
              <label>结算类型</label>
              <select v-model="createForm.settlementType">
                <option value="">请选择</option>
                <option :value="0">现结</option>
                <option :value="1">月结</option>
                <option :value="2">货到付款</option>
              </select>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>状态</label>
              <select v-model="createForm.status">
                <option value="">请选择</option>
                <option :value="1">待付款</option>
                <option :value="2">部分付款</option>
                <option :value="3">已付款</option>
                <option :value="4">坏账</option>
              </select>
            </div>
            <div class="form-group">
              <label>到期日</label>
              <input type="date" v-model="createForm.dueDate" :min="new Date().toISOString().split('T')[0]">
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="required">应付金额</label>
              <input type="number" v-model="createForm.payableAmount" placeholder="请输入应付金额" step="0.01" @input="calculateUnpaidAmount">
            </div>
            <div class="form-group">
              <label>已付金额</label>
              <input type="number" v-model="createForm.paidAmount" placeholder="请输入已付金额" step="0.01" @input="calculateUnpaidAmount">
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>未付金额</label>
              <input type="number" v-model="createForm.unpaidAmount" placeholder="自动计算" readonly>
            </div>
            <div class="form-group">
              <label>付款条件</label>
              <input type="text" v-model="createForm.paymentTerm" placeholder="请输入付款条件" maxlength="100">
            </div>
          </div>

          <div class="form-row">
            <div class="form-group full-width">
              <label>备注</label>
              <textarea v-model="createForm.remark" placeholder="请输入备注" rows="3" maxlength="200"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-cancel" @click="closeCreate" :disabled="createLoading">取消</button>
          <button class="btn-save" @click="submitCreate" :disabled="createLoading">
            {{ createLoading ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 详情 -->
    <div v-if="showDetail" class="detail-drawer">
      <div class="drawer-body">
        <div class="drawer-header">
          <span>{{ detail?.payableNo }} - 应付明细详情</span>
          <button class="btn-secondary" @click="showDetail=false">关闭</button>
        </div>
        <div class="drawer-content">
          <div class="section">
            <div class="section-title">基本信息</div>
            <div class="form-grid">
              <div class="form-item">
                <label>应付编号</label>
                <span>{{ detail?.payableNo || '-' }}</span>
              </div>
              <div class="form-item">
                <label>供应商</label>
                <span>{{ detail?.supplierName || detail?.supplierId || '-' }}</span>
              </div>
              <div class="form-item">
                <label>采购订单</label>
                <span>{{ detail?.purchaseOrderNo || detail?.purchaseOrderId || '-' }}</span>
              </div>
              <div class="form-item">
                <label>应付类型</label>
                <span>{{ detail?.payableType === 1 ? '采购应付' : detail?.payableType === 2 ? '其他应付' : '-' }}</span>
              </div>
              <div class="form-item">
                <label>状态</label>
                <span>{{ fmtStatus(detail?.status) }}</span>
              </div>
              <div class="form-item">
                <label>结算类型</label>
                <span>{{ fmtSettlement(detail?.settlementType) }}</span>
              </div>
            </div>
          </div>

          <div class="section">
            <div class="section-title">金额信息</div>
            <div class="form-grid">
              <div class="form-item">
                <label>应付金额</label>
                <span>{{ fmtMoney(detail?.payableAmount) }}</span>
              </div>
              <div class="form-item">
                <label>已付金额</label>
                <span>{{ fmtMoney(detail?.paidAmount) }}</span>
              </div>
              <div class="form-item">
                <label>未付金额</label>
                <span>{{ fmtMoney(detail?.unpaidAmount) }}</span>
              </div>
              <div class="form-item">
                <label>到期日</label>
                <span>{{ fmtDate(detail?.dueDate) }}</span>
              </div>
              <div class="form-item">
                <label>付款条件</label>
                <span>{{ detail?.paymentTerm || '-' }}</span>
              </div>
              <div class="form-item">
                <label>备注</label>
                <span>{{ detail?.remark || '-' }}</span>
              </div>
            </div>
          </div>

          <div class="section">
            <div class="section-title">系统信息</div>
            <div class="form-grid">
              <div class="form-item">
                <label>创建时间</label>
                <span>{{ fmtDateTime(detail?.createTime) }}</span>
              </div>
              <div class="form-item">
                <label>更新时间</label>
                <span>{{ fmtDateTime(detail?.updateTime) }}</span>
              </div>
              <div class="form-item">
                <label>创建人</label>
                <span>{{ detail?.creator || '-' }}</span>
              </div>
        </div>
        </div>
      </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <div v-if="loading" class="table-loading-overlay">
        <div class="loading-text">加载中...</div>
      </div>
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>结算类型</th>
            <th>供应商</th>
            <th>采购订单</th>
            <th>应付金额</th>
            <th>已付金额</th>
            <th>未付金额</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in tableData" :key="row.id">
            <td><input type="checkbox" v-model="row._selected"></td>
            <td>{{ fmtSettlement(row.settlementType) }}</td>
            <td>{{ row.supplierName || row.supplierId }}</td>
            <td>{{ row.purchaseOrderNo || row.purchaseOrderId }}</td>
            <td>{{ fmtMoney(row.payableAmount) }}</td>
            <td>{{ fmtMoney(row.paidAmount) }}</td>
            <td>{{ fmtMoney(row.unpaidAmount) }}</td>
            <td>{{ fmtStatus(row.status) }}</td>
            <td>
              <button class="btn-link" @click="viewDetail(row)">查看</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <div class="batch-actions">
        <label class="select-all">
        <input type="checkbox" v-model="allSelected">
          全选
        </label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination-controls">
        <button class="btn-pagination" @click="changePage(pageNum - 1)" :disabled="pageNum <= 1">‹</button>
        <button class="btn-pagination active" disabled>{{ pageNum }}</button>
        <button class="btn-pagination" @click="changePage(pageNum + 1)" :disabled="pageNum >= totalPages">›</button>
        <select v-model="pageSize" @change="reload">
          <option :value="5">5条/页</option>
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
        </select>
      </div>
    </div>
  </div>
</template>

<script>
import { payablePage, payableInfo, payableCreate } from '@/api/finance/payableDetail'

export default {
  name: 'AccountsPayableDetail',
  data() {
    return {
      // 筛选条件
      keyword: '',
      settlementType: '',
      // 分页
      pageNum: 1,
      pageSize: 5,
      total: 0,
      // 表格数据
      tableData: [],
      // 详情
      showDetail: false,
      detail: null,
      // 新建
      showCreate: false,
      createForm: {
        payableNo: '',
        supplierId: null,
        purchaseOrderId: null,
        reconciliationId: null,
        payableType: null,
        payableAmount: null,
        paidAmount: null,
        unpaidAmount: null,
        dueDate: '',
        status: null,
        settlementType: null,
        paymentTerm: '',
        remark: ''
      },
      // 加载状态
      loading: false,
      createLoading: false
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.tableData.length > 0 && this.tableData.every(item => item._selected);
      },
      set(value) {
        this.tableData.forEach(item => {
          item._selected = value;
        });
      }
    },
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.pageSize))
    }
  },
  mounted() {
    this.reload()
  },
  methods: {
    onSearch() {
      this.pageNum = 1
      this.reload()
    },
    onReset() {
      this.pageNum = 1
      this.pageSize = 10
      this.settlementType = ''
      this.keyword = ''
      this.reload()
    },
    async reload() {
      this.loading = true
      try {
        const payload = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          payableNo: this.keyword || undefined,
          settlementType: this.settlementType === '' ? undefined : Number(this.settlementType)
        }
        const { data } = await payablePage(payload)
        const page = data?.data || data // 兼容两种返回
        this.total = page.total || 0
        this.tableData = (page.records || []).map(it => ({ ...it, _selected: false }))
      } catch (error) {
        console.error('加载数据失败:', error)
      } finally {
        this.loading = false
      }
    },
    changePage(p) {
      if (p < 1) return
      this.pageNum = p
      this.reload()
    },
    async viewDetail(row) {
      const id = row?.id
      if (!id) return
      const { data } = await payableInfo(id)
      this.detail = data?.data || data
      this.showDetail = true
    },
    fmtMoney(v) {
      if (v === null || v === undefined) return '-'
      const n = Number(v)
      if (Number.isNaN(n)) return String(v)
      return n.toFixed(2)
    },
    fmtDate(ts) {
      if (!ts) return '-'
      const d = new Date(ts)
      if (Number.isNaN(d.getTime())) return '-'
      return d.toISOString().slice(0, 10)
    },
    fmtDateTime(ts) {
      if (!ts) return '-'
      const d = new Date(ts)
      if (Number.isNaN(d.getTime())) return '-'
      return d.toISOString().replace('T', ' ').slice(0, 19)
    },
    fmtStatus(s) {
      const map = { 1: '待付款', 2: '部分付款', 3: '已付款', 4: '坏账' }
      return map[s] || '-'
    },
    fmtSettlement(s) {
      const map = { 0: '现结', 1: '月结', 2: '货到付款' }
      return map[s] ?? '-'
    },
    // 新建功能
    closeCreate() {
      this.showCreate = false
      this.resetCreateForm()
    },
    resetCreateForm() {
      this.createForm = {
        payableNo: '',
        supplierId: null,
        purchaseOrderId: null,
        reconciliationId: null,
        payableType: null,
        payableAmount: null,
        paidAmount: null,
        unpaidAmount: null,
        dueDate: '',
        status: null,
        settlementType: null,
        paymentTerm: '',
        remark: ''
      }
    },
    calculateUnpaidAmount() {
      const payable = parseFloat(this.createForm.payableAmount) || 0
      const paid = parseFloat(this.createForm.paidAmount) || 0
      this.createForm.unpaidAmount = Math.max(0, payable - paid)
    },
    async submitCreate() {
      this.createLoading = true
      try {
        // 数据验证
        if (!this.createForm.payableNo?.trim()) {
          alert('请输入应付编号')
          this.createLoading = false
          return
        }
        if (!this.createForm.supplierId) {
          alert('请输入供应商ID')
          this.createLoading = false
          return
        }
        if (!this.createForm.payableAmount || this.createForm.payableAmount <= 0) {
          alert('请输入有效的应付金额')
          this.createLoading = false
          return
        }

        // 验证已付金额不能超过应付金额
        if (this.createForm.paidAmount && this.createForm.paidAmount > this.createForm.payableAmount) {
          alert('已付金额不能超过应付金额')
          this.createLoading = false
          return
        }

        // 转换数据类型
        const payload = {
          ...this.createForm,
          supplierId: this.createForm.supplierId ? Number(this.createForm.supplierId) : null,
          purchaseOrderId: this.createForm.purchaseOrderId ? Number(this.createForm.purchaseOrderId) : null,
          reconciliationId: this.createForm.reconciliationId ? Number(this.createForm.reconciliationId) : null,
          payableType: this.createForm.payableType ? Number(this.createForm.payableType) : null,
          payableAmount: this.createForm.payableAmount ? Number(this.createForm.payableAmount) : null,
          paidAmount: this.createForm.paidAmount ? Number(this.createForm.paidAmount) : null,
          status: this.createForm.status ? Number(this.createForm.status) : null,
          settlementType: this.createForm.settlementType ? Number(this.createForm.settlementType) : null
        }

        const { data } = await payableCreate(payload)
        if (data?.code === 200) {
          alert('应付明细创建成功！')
          this.closeCreate()
          this.reload() // 刷新列表
        } else {
          alert('创建失败: ' + (data?.msg || '未知错误'))
        }
      } catch (error) {
        console.error('创建失败:', error)
        alert('创建失败: ' + error.message)
      } finally {
        this.createLoading = false
      }
    },
  }
}
</script>

<style scoped>
.payable-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filters {
    display: flex;
  align-items: center;
    gap: 16px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
}

.filter-item select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background-color: #fff;
  font-size: 14px;
  min-width: 120px;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-primary {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 6px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  height: 32px;
}

.btn-primary:hover {
  background-color: #40a9ff;
}

.btn-secondary {
  background-color: #fff;
  color: #333;
  border: 1px solid #d9d9d9;
  padding: 6px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  height: 32px;
}

.btn-secondary:hover {
  color: #1890ff;
  border-color: #40a9ff;
}

.btn-link {
  background: none;
  border: none;
  color: #1890ff;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
}

.btn-link:hover {
  color: #40a9ff;
}

.btn-pagination {
  background-color: #fff;
  color: #333;
  border: 1px solid #d9d9d9;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-pagination:hover:not(:disabled) {
  color: #1890ff;
  border-color: #40a9ff;
}

.btn-pagination.active {
  background-color: #1890ff;
  color: #fff;
  border-color: #1890ff;
}

.btn-pagination:disabled {
  color: #ccc;
  border-color: #f0f0f0;
  cursor: not-allowed;
}

.table-section {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

th {
  background-color: #fafafa;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #e8e8e8;
}

tbody tr:hover {
  background-color: #f5f5f5;
}

tbody tr:last-child td {
  border-bottom: none;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-top: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.select-all input[type="checkbox"] {
  margin: 0;
}

.page-info {
  font-size: 14px;
  color: #333;
  margin: 0 8px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-controls select {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background-color: #fff;
  font-size: 14px;
  height: 32px;
}

.detail-drawer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.45);
  z-index: 1000;
  /* drawer overlay; panel aligns to the right */
  display: block;
}

.drawer-body {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 800px;
  max-width: 90vw;
  background: #fff;
  box-shadow: -2px 0 12px rgba(0, 0, 0, 0.15);
  overflow-y: auto;
  border-radius: 0;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.drawer-content {
  padding: 20px;
}

.section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #1890ff;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-item label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.form-item span {
  font-size: 14px;
  color: #333;
  padding: 8px 0;
}

/* 加载状态样式 */
.table-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-text {
  color: #1890ff;
  font-size: 14px;
}

/* 新建模态框样式 */
.create-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  background: white;
  border-radius: 4px;
  width: 600px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  background: #87ceeb;
  color: white;
  padding: 16px 20px;
  border-radius: 4px 4px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 16px;
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.modal-body {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  flex: 1;
}

.form-group label {
  font-size: 14px;
  color: #333;
  margin-bottom: 6px;
  font-weight: 500;
}

.form-group label.required {
  color: #f56c6c !important;
}

.form-group label.required::after {
  content: " *";
  color: #f56c6c !important;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
  background: white;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.form-group input[readonly] {
  background-color: #f5f5f5;
  color: #666;
  cursor: not-allowed;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn-cancel {
  padding: 8px 20px;
  border: 1px solid #d9d9d9;
  background: white;
  color: #333;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-cancel:hover:not(:disabled) {
  border-color: #40a9ff;
  color: #1890ff;
}

.btn-save {
  padding: 8px 20px;
  border: none;
  background: #1890ff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.btn-save:hover:not(:disabled) {
  background: #40a9ff;
}

.btn-cancel:disabled,
.btn-save:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
